package com.school.information.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.school.information.dto.WechatAppUserDTO;
import com.school.information.entity.SysWechatUserEntity;
import com.school.information.enums.result.SysResultEnum;
import com.school.information.service.SysWechatUserService;
import com.school.information.utils.ResultUtil;
import com.school.information.utils.UserUtil;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * (SysWechatUser)表控制层
 *
 * @author ycc
 * @since 2023-11-15 14:25:49
 */
@RestController
@RequestMapping("sysWechatUser")
public class SysWechatUserController {
    /**
     * 服务对象
     */
    @Resource
    private SysWechatUserService sysWechatUserService;

    /**
     * 接收小程序传递的用户数据进行解密，将数据信息进行保存
     *
     * @param wechatAppUser
     * @return
     */
    @PutMapping("/update")
    public ResultUtil update(@RequestBody @Valid WechatAppUserDTO wechatAppUser) {
        if (ObjectUtil.isEmpty(wechatAppUser)) {
            return ResultUtil.ERROR_ARG;
        }
        // 根据加密数据和session_key进行解密，获取数据
        String data = sysWechatUserService.decryptWechatData(wechatAppUser);
        SysWechatUserEntity sysWechatUser = JSONUtil.toBean(data, SysWechatUserEntity.class);
        // 根据当前用户登录的openid 获取用户信息
        SysWechatUserEntity oldWechatUser = sysWechatUserService.getByOpenid(UserUtil.getWechatUserOpenid());
        BeanUtil.copyProperties(sysWechatUser, oldWechatUser);
        if (sysWechatUserService.updateById(oldWechatUser)) {
            return ResultUtil.SUCCESS_NO_DATA;
        }
        return ResultUtil.error(SysResultEnum.WECHAT_USER_UPDATE_FAIL);
    }
}

